<template>
  <qx-table v-model:selected="selected" :option="tableOption" :remoteData="remoteData">
    <template v-slot:top>
      <span class="text-h6">{{ $t('SystemCore.BasicInformation') }}</span>
      <q-separator></q-separator>
      <qx-form v-model="formInfo" :option="formOption"></qx-form>
      <span class="text-h6">{{ $t('SystemCore.AssignRole') }}</span>
    </template>
  </qx-table>
</template>

<script setup>
import { i18n, toI18nName } from 'boot/i18n'
import { postAPI } from 'src/api'
import { yesOrNo } from 'src/enum'
import { computed, onMounted, ref, watch } from 'vue'

const props = defineProps({ list: Array, rowInfo: Object, readonly: Boolean, modelValue: Boolean })

const formInfo = ref({})
const selected = ref([])

watch(() => props.modelValue, val => {
  if (!val) return
  selected.value = props.list || []
  formInfo.value = props.rowInfo || {}
}, { immediate: true })

const formOption = computed(() => {
  return {
    span: 8, readonly: true, menuBtn: false,
    column: [{
      label: `${i18n.t('Account')}`, field: 'loginName'
    }, {
      label: `${i18n.t('SystemCore.Name')}`, field: 'nickName'
    }]
  }
})

const tableOption = computed(() => {
  return {
    page: false, searchBtn: false, selection: 'multiple', selectable: !props.readonly,
    column: [{
      label: `${i18n.t('SystemCore.RoleCode')}`,
      field: 'roleCode', minWidth: 80
    }, {
      label: `${i18n.t('SystemCore.RoleName')}`,
      field: 'roleNameZhCn', minWidth: 80,
      format: (_, row) => row[toI18nName('roleNameZhCn')]
    }, {
      label: `${i18n.t('BuiltIn')}`, field: 'sysInner', minWidth: 80,
      options: yesOrNo.value, useTag: true
    }, {
      label: `${i18n.t('Remarks')}`, field: 'remark', minWidth: 120
    }]
  }
})

const remoteData = ref({ dicUrl: '/auth/api/authRole/listAuthRole' })

onMounted(() => {
  remoteData.value.params = { pageSize: '-1' }
})

const submitRole = done => {
  const params = { userId: formInfo.value.id, roleIds: selected.value.map(el => el.id) }
  postAPI('/auth/api/authRole/resetUsers', params, () => done(), () => done(false))
}

defineExpose({ submitRole })
</script>